<script>
import dayjs from 'dayjs';
import { ElMessageBox, ElMessage } from 'element-plus';

export default {
  name: "student list",
  data() {
    return {
      students: [],
      visible: false,
      student: {
        id: '',
        name: '',
        gender: '',
        birthdate: '',
        hometown: ''
      }
    };
  },
  methods: {
    loadAll() {
      // 异步抓取服务端数据
      const p = fetch("/api/student");
      p.then( resp => resp.json())
       .then( data =>  this.students = data.students)
       .catch( error => {
          console.dir(error);
       });
    },
    remove({ id, name }) {
      const p = ElMessageBox.confirm(`你确定删除${name}吗?`, '警告', {
        /*区分 取消 和 关闭 操作*/
        distinguishCancelAndClose: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定'
      });

      p.then( () => fetch(`/api/student?id=${id}`, { method: 'DELETE'}) )
       .then( resp => resp.json() )
       .then( res => {
          if( res.success ) {
            ElMessage({
              message: `已经成功删除${name}.`,
              type: 'success',
            })
            // 重新加载数据
            this.loadAll();
          }
       }).catch( reason => {
          console.log( 'reason:', reason );
       });
    },
    edit(stu) {
      // 将表格中被编辑行的数据克隆到 this.student 对象
      Object.assign( this.student, stu );
      this.visible = true;
    },
    cancel() {
      this.visible = false;
    },
    confirm() {
      const p = ElMessageBox.confirm(`你确定修改该学生吗?`, '警告', {
        distinguishCancelAndClose: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定'
      });

      const s = this.student;
      const dateOfBirth = dayjs(s.birthdate).format('YYYY-MM-DD');
      console.log( dateOfBirth );

      const init = { 
        method: 'PUT', 
        headers:{
          'content-type': 'application/x-www-form-urlencoded'
        },
        body: `id=${s.id}&name=${s.name}&gender=${s.gender}&hometown=${s.hometown}&dateOfBirth=${dateOfBirth}`
      }

      p.then( () => fetch('/api/student', init ) )
       .then( resp => resp.json() )
       .then( data => {
          if( data.success ) {
            // 重新加载数据
            this.loadAll();
            // 隐藏对话框
            this.visible = false;
            return;
          }
          console.log( data.message );
       }).catch( reason => {
          if( reason == 'cancel' ) {
            console.log( '取消修改' );
            return;
          }
          if( reason instanceof Error ) {
            console.error( reason );
          }
       });
    },
    detail({id}) {
      // fetch(`/api/student?id=${id}`)
    }
  },
  created() {
    this.loadAll();
  },
};
</script>

<template>
  <div class="student-list">
    <h3>学生列表</h3>
    <el-table :data="students" style="width: 100%" :stripe="true">
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="gender" label="性别" width="100" />
        <el-table-column prop="birthdate" label="出生日期" width="200" />
        <el-table-column prop="hometown" label="籍贯" />
        <el-table-column label="操作">
          <!--作用域插槽-->
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="detail(row)">详情</el-button>
            <el-button type="primary" size="small" @click="edit(row)">编辑</el-button>
            <el-button type="primary" size="small" @click="remove(row)">删除</el-button>
          </template>
        </el-table-column>
    </el-table>
    <!--对话框-->
    <el-dialog v-model="visible">
      <!--为具名插槽(header)分发内容-->
      <template #header>
        <b>修改学生信息</b>
      </template>
      <!--为默认的插槽(default)分发内容-->
      <template #default>
        <el-form :model="student" label-width="120px">
          <el-form-item label="姓名">
              <el-input v-model="student.name"></el-input>
          </el-form-item>
          <el-form-item label="性别">
              <el-radio-group v-model="student.gender">
                  <el-radio label="male" size="large">靓仔</el-radio>
                  <el-radio label="female" size="large">靓妹</el-radio>
              </el-radio-group>
          </el-form-item>
          <el-form-item label="出生日期">
              <el-date-picker v-model="student.birthdate" type="date" :editable="false" />
          </el-form-item>
          <el-form-item label="籍贯">
              <el-input v-model="student.hometown"></el-input>
          </el-form-item>
      </el-form>
      </template>
      <!--为具名插槽(footer)分发内容-->
      <template #footer>
        <el-button type="default" @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style>
</style>